package com.java.jetpackdemo.room

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData

/**
 * 注意：一定不能传自定义的MyApplication，要传系统的Application
 */
class UserViewModel(application: Application) : AndroidViewModel(application) {
    private var userDao: UserDao
    private lateinit var listUser: LiveData<MutableList<UserBean>>

    init {
        val db = UserDataBase.instance
        userDao = db.userDao()
    }


    fun selectAll(): LiveData<MutableList<UserBean>> {
        listUser = userDao.getAll()
        return listUser
    }

    fun insert() {
        val userBean = UserBean(name = "张三", age = 18, sex = "男")
        userDao.insertUser(userBean)
    }

    fun delete() {
        val userBean = UserBean(name = "张三", age = 18, sex = "男")
        userBean.id = 11
        userDao.deleteUser(userBean)
    }

    fun update() {
        val userBean = UserBean(name = "小红", age = 17, sex = "女")
        userBean.id = 10
        userDao.updateUser(userBean)
    }

    fun deleteAll() {
        userDao.deleteAll()
        listUser.value?.clear()
    }
}